import { LabelWithTips } from "@renderer/components/business/label-with-tips";
import {
  FieldError,
  FieldGroup,
  Input,
  Label,
} from "@renderer/components/ui/base/field";
import { TextField } from "@renderer/components/ui/base/text-field";
import { isUndefined } from "es-toolkit";
import { useState } from "react";
import { useTranslation } from "react-i18next";

interface ParametersInputProps {
  label: string;
  tips?: string;

  value: number | null;
  onChange: (value: number | null) => void;
}

export function ParametersInput({
  label,
  tips,
  value,
  onChange,
}: ParametersInputProps) {
  const { t } = useTranslation("translation", {
    keyPrefix: "chat.tool-bar.parameters.maxTokens",
  });

  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const validateInteger = (inputValue: string): boolean => {
    if (inputValue === "") return true;

    const num = Number(inputValue);
    return Number.isInteger(num) && num >= 1;
  };

  const handleValueChange = (value: string) => {
    if (value.trim() === "") {
      setErrorMessage(null);
      onChange(null);
      return;
    }

    if (!validateInteger(value)) {
      setErrorMessage(t("errorMessage.integer"));
      return;
    }

    setErrorMessage(null);
    onChange(Number(value));
  };

  return (
    <TextField
      className="flex flex-col"
      value={value ? value.toString() : ""}
      isInvalid={!!errorMessage}
      onChange={(value) => handleValueChange(value)}
    >
      <div className="flex flex-1 flex-row justify-between">
        {isUndefined(tips) ? (
          <Label className="text-label-fg">{label}</Label>
        ) : (
          <LabelWithTips label={label} tips={tips} tooltipPlacement="right" />
        )}
        <FieldGroup className="h-7 w-20 bg-setting" isInvalid={!!errorMessage}>
          <Input placeholder={t("placeholder")} />
        </FieldGroup>
      </div>

      <FieldError className="self-end">{errorMessage}</FieldError>
    </TextField>
  );
}
